package com.gitee.yongzhuzl.commonutil.util.code.bcrypt;

import com.gitee.yongzhuzl.commonutil.util.empty.EmptyUtil;
import com.gitee.yongzhuzl.commonutil.util.md5.Md5Util;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * description: BCrypt加密工具类
 * @author 朱正磊
 * @date 2022-05-16 18:56:02
 */
public class BCryptUtil {

    /**
     * description: 对明文进行BCrypt加密
     * @author 朱正磊
     * @date 2022-05-16 19:23:36
     * @param rawPassword 明文
     * @param md5 在进行BCrypt加密之前是否需要先进行md5加密，true需要，false不需要
     * @return 返回密文
     */
    public static String encode(String rawPassword, Boolean md5) {
        if (EmptyUtil.isEmpty(rawPassword)) {
            throw new RuntimeException("明文不能为空！");
        }
        if (md5) {
            return new BCryptPasswordEncoder().encode(Md5Util.md5(rawPassword));
        }
        return new BCryptPasswordEncoder().encode(rawPassword);
    }

    /**
     * description: 校验明文和密文是否匹配
     * @author 朱正磊
     * @date 2022-05-16 19:30:20
     * @param rawPassword 明文
     * @param encodedPassword 密文
     * @return 校验成功返回true，否则返回false
     */
    public static Boolean matches(String rawPassword, String encodedPassword) {
        if (EmptyUtil.isEmpty(rawPassword)) {
            throw new RuntimeException("明文不能为空！");
        }
        if (EmptyUtil.isEmpty(encodedPassword)) {
            throw new RuntimeException("密文不能为空！");
        }
        return new BCryptPasswordEncoder().matches(rawPassword, encodedPassword);
    }

}
